const config = {
    database: {
        DATABASE: 'mgmusic',
        USERNAME: 'root',
        PASSWORD: '123456',
        PORT: '3306',
        HOST: 'localhost'
    }
}

let mysql = require('mysql');

let pool = mysql.createPool({
    host: config.database.HOST,
    user: config.database.USERNAME,
    password: config.database.PASSWORD,
    database: config.database.DATABASE,
    dateStrings:true
});


// 将结果以对象数组返回
const row = (sql, ...params) => {
    return new Promise((resolve, reject) => {

        pool.getConnection((err, connection) => {
            if (err) {
                reject(err);
                return;
            }
            connection.query(sql, [params], (error, res) => {
                connection.release();
                if (error) {
                    reject(error);
                    return;
                }
                resolve(res);
            })
        })
    })
}

// 返回一个对象
const resultObj = (sql, ...params) => {
    return new Promise((resolve, reject) => {

        pool.getConnection((err, connection) => {
            if (err) {
                reject(err);
                return;
            }
            connection.query(sql, params, (error, res) => {
                connection.release();
                if (error) {
                    reject(error);
                    return;
                }
                resolve(res[0] || null);
            })
        })
    })
}

//返回单个查询结果
const single = (sql, ...params) => {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                reject(err);
                return;
            }
            connection.query(sql, params, (error, res) => {
                if (error) {
                    reject(error);
                    return;
                }
                for (let i in res[0]) {
                    resolve(res[0][i] || null);
                    return;
                }
                resolve(null);
            })
        })
    })
}

const execute = (sql, ...params) => {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                reject(err);
                return;
            }
            connection.query(sql, params, (error, res) => {
                connection.release();
                if (error) { reject(error); return; }
                resolve(res);
            })
        })
    })
}

module.exports = {
    row,
    resultObj,
    single,
    execute
}